<template>
  <div class="control_right">
    <div id="containerMap"></div>
    <div class="right_tab">
      <el-tabs v-model="activeName" @tab-click="handleClick" :stretch="true" style="width: 50%; display: flex; align-items: center; padding-top: 11px">
        <el-tab-pane name="0">
          <span slot="label"> 全部</span>
        </el-tab-pane>
        <el-tab-pane name="1">
          <div slot="label" class="tabitem">
            <img src="./../../../assets/img/index/motor1.png" alt="" />
            <span>上班</span>
          </div>
        </el-tab-pane>
        <el-tab-pane name="2">
          <div slot="label" class="tabitem">
            <img src="./../../../assets/img/index/motor2.png" alt="" />
            <span>下班</span>
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane name="3">
          <div slot="label" class="tabitem">
            <img src="./../../../assets/img/index/motor3.png" alt="" />
            <span>空闲中（离线）</span>
          </div>
        </el-tab-pane>
        <el-tab-pane name="4">
          <div slot="label" class="tabitem">
            <img src="./../../../assets/img/index/motor4.png" alt="" />
            <span> 接单中（离线）</span>
          </div>
        </el-tab-pane> -->
      </el-tabs>
    </div>
  </div>
</template>
<script>
const IntervalTime = 15000;
const GPSKEY = "9ea145d7d33cad98b37ddb1eb43dcb2d";
export default {
  name: "control_right",
  data() {
    return {
      audioObj: null,
      waitArr: [],
      waitorderlist: [],
      timer: null,
      pointArr: [],
      driver_num: 0,
      driver_list: [],
      activeName: "0",
      map: null,
      polygon: null,
    };
  },
  components: {},
  created() {
    this.initMap();
    var that = this;
    window.onLoad = () => {
      that.init();
    };
  },
  destroyed: function () {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    playAudio() {
      if (!this.audioObj) {
        var file = require("./../../../assets/audio/neworder.mp3");
        this.audioObj = new Audio();
        this.audioObj.src = file;
        this.audioObj.play();
      }
    },
    getWaitDriverOrder() {
      var params = {};

      var that = this;
      // params.status = "待接单";
      params.page = 1;
      params.page_size = 10;
      if (this.$route.query.id) {
        params.sid = this.$route.query.id;
      }
      var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
      function infoClose(e) {
        infoWindow.close(that.map, e.target.getPosition());
      }
      function infoOpen(e) {
        infoWindow.setContent(e.target.content);
        infoWindow.open(that.map, e.target.getPosition());
      }

      this.$api.getRider.getRiderList(params).then((res) => {
        if (res.data.code == 200) {
          if (res.data.result && res.data.result.all_num2 > 0) {
            this.playAudio();
          }
          this.waitorderlist = res.data.result.data;
          //绘制点
          that.map.remove(that.waitArr);
          that.waitArr = [];
          this.waitorderlist.forEach((item, i) => {
            if (item.status == "待接单" || item.status == "已派单") {
              console.log(item);
              var dot = `<img src="${require("./../../../assets/img/index/01.png")}" alt="" style="width:30px"/>`;
              if (Number(item.open_longitude) == 0 && Number(item.open_latitude) == 0) {
                return;
              }
              var marker = new AMap.Marker({
                position: new AMap.LngLat(item.open_longitude, item.open_latitude),
                // animation: "AMAP_ANIMATION_DROP",
                anchor: "bottom-center", //设置锚点
                offset: new AMap.Pixel(0, 0), //设置偏移量
                content: dot,
                map: that.map,
              });
              marker.content = `<h3 style="display:flex;align-items:center">
            <img src="${item.avatar}" alt="" style="border-radius:50%;width:30px;height:30px;margin-right:5px">  
            下单用户：${item.nickname || item.username}</h3>`;
              marker.content += `<div>起点：${item.open_address}</div>`;
              marker.content += `<div>终点：${item.end_address}</div>`;
              marker.on("mouseover", infoOpen);
              marker.on("mouseout", infoClose);
              that.waitArr.push(marker);
            }
          });
          console.log(that.waitArr);
          that.map.add(that.waitArr);
        }
      });
    },
    setTimer() {
      if (this.timer == null) {
        this.timer = setInterval(() => {
          this.getAllDriver(false);
          this.getWaitDriverOrder(false);
        }, IntervalTime);
      }
    },
    handleClick(tab, event) {
      this.getAllDriver({});
    },
    getAllDriver(flag = true) {
      var params = {};
      switch (true) {
        case this.activeName == "1":
          params.is_rider_work = 1; //上班
          break;
        case this.activeName == "2": //下班
          params.is_rider_work = 0;
          break;
        // case this.activeName == "3":
        //   params.work_status = 0;
        //   params.order_status = 0;
        //   break;
        // case this.activeName == "4":
        //   params.work_status = 0;
        //   params.order_status = 1;
        //   break;
        default:
          break;
      }
      var that = this;
      that.map.remove(that.pointArr);
      var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
      function infoClose(e) {
        infoWindow.close(that.map, e.target.getPosition());
      }
      function infoOpen(e) {
        infoWindow.setContent(e.target.content);
        infoWindow.open(that.map, e.target.getPosition());
      }

      if (this.$route.query.id && this.$route.query.id > 0) {
        params.sid = this.$route.query.id;
      }
      params.page_size = 999;
      this.$api.getRider.getRiderList(params).then((res) => {
        if (res.data.code == 200) {
          this.driver_list = res.data.result.data;
          this.driver_num = res.data.result.all_sum;
          //绘制点
          that.pointArr = [];
          this.driver_list.forEach((item, i) => {
            var dot = "";
            if (Number(item.longitude) == 0 && Number(item.latitude) == 0) {
              return;
            }
            switch (true) {
              case item.is_rider_work == 1:
                //上班中
                dot = `<img src="${require("./../../../assets/img/index/motor1.png")}" alt="" style="width:30px"/>`;
                break;
              case item.is_rider_work == 0:
                //下班中
                dot = `<img src="${require("./../../../assets/img/index/motor2.png")}" alt="" style="width:30px"/>`;
                break;
              // case item.work_status == 0 && item.order_status == 0:
              //   //空闲中（离线）
              //   dot = `<img src="${require("./../../../assets/img/index/motor3.png")}" alt="" style="width:30px"/>`;
              //   break;
              // case item.work_status == 0 && item.order_status == 1:
              //   //接单中（离线）
              //   dot = `<img src="${require("./../../../assets/img/index/motor4.png")}" alt="" style="width:30px"/>`;
              //   break;
              default:
                break;
            }
            var marker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              // animation: "AMAP_ANIMATION_DROP",
              anchor: "bottom-center", //设置锚点
              offset: new AMap.Pixel(0, 0), //设置偏移量
              content: dot,
              map: that.map,
            });
            marker.content = `<h3 style="display:flex;align-items:center">
            <img src="${item.avatar}" alt="" style="border-radius:50%;width:30px;height:30px;margin-right:5px">  
            服务人员：${item.name || item.nickname || item.username}</h3>`;
            marker.content += `<div style='margin-top:10px'>上班状态：${item.is_rider_work == 1 ? "上班" : "下班"}</div>`;
            marker.on("mouseover", infoOpen);
            marker.on("mouseout", infoClose);
            that.pointArr.push(marker);
          });
          console.log(that.pointArr);
          that.map.add(that.pointArr);
          if (flag === true) {
            that.map.setFitView();
          }
        }
      });
    },
    setArea() {
      if (this.$route.query.id) {
        this.$api.getUser.extractEdit({ id: this.$route.query.id }).then((res) => {
          if (res.data.code == 200) {
            let areaList = [];
            if (res.data.result.map && res.data.result.map != "[]") {
              areaList = JSON.parse(res.data.result.map);
              this.polygon = new AMap.Polygon({
                path: areaList,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                fillColor: "#1791fc",
                zIndex: 50,
                bubble: true,
              });
              this.map.add([this.polygon]);
            }
          }
        });
      }
    },
    init() {
      var that = this;
      that.map = new AMap.Map("containerMap", {
        resizeEnable: true,
        mapStyle: "amap://styles/light",
        zoom: 12,
      });

      that.map.plugin(["AMap.ControlBar", "AMap.MapType", "AMap.Scale"], function () {
        var controlBar = new AMap.ControlBar({
          showZoomBar: true,
          showControlButton: true,
          position: { bottom: "0px", right: "10px" },
        });
        //地图类型切换
        var type = new AMap.MapType({
          defaultType: 0, //使用2D地图
        });
        var scale = new AMap.Scale();
        that.map.addControl(controlBar);
        that.map.addControl(scale);
        that.map.addControl(type);
      });
      that.setArea();
      that.getAllDriver();
      that.getWaitDriverOrder();
      that.setTimer();
    },
    initMap() {
      var url = `https://webapi.amap.com/maps?v=1.4.15&key=${GPSKEY}&callback=onLoad&plugin=AMap.Driving`;
      var jsapi = document.createElement("script");
      jsapi.charset = "utf-8";
      jsapi.src = url;
      document.head.appendChild(jsapi);
    },
  },
};
</script>
<style lang="less">
.control_right {
  width: 100%;
  height: 100%;
  position: relative;
  #containerMap {
    width: 100%;
    height: 100%;
  }
  /deep/.el-tabs__header {
    width: 100%;
  }
  .right_tab {
    position: absolute;
    top: 20px;
    left: 0;
    right: 0;
    margin: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    > div {
      background-color: #fff;
      padding: 0 50px;
    }
  }
  .tabitem {
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 25px;
    }
    span {
      font-size: 14px;
      line-height: 1.2;
    }
  }
}
.el-tabs__nav {
  display: flex !important;
}
</style>
